package com.ruoyi.biz.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.biz.domain.BizGame;
import com.ruoyi.biz.domain.BizPan;
import com.ruoyi.biz.pojo.vo.BizFileVO;
import com.ruoyi.biz.service.IBizGameService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.biz.domain.BizFile;
import com.ruoyi.biz.service.IBizFileService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 游戏附件Controller
 *
 * @author jason
 * @date 2025-10-31
 */

@Controller
@RequestMapping("/biz/file")
public class BizFileController extends BaseController {
    private String prefix = "biz/file";

    @Autowired
    private IBizFileService bizFileService;

    @Autowired
    IBizGameService bizGameService;

    @RequiresPermissions("biz:file:view")
    @GetMapping()
    public String file() {
        return prefix + "/file";
    }

    /**
     * 查询游戏附件列表
     */
    @RequiresPermissions("biz:file:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BizFile bizFile) {
        startPage();
        List<BizFile> list = bizFileService.selectBizFileList(bizFile);
        List<BizFileVO> vos = BeanUtil.copyToList(list, BizFileVO.class);
        List<Long> ids = list.stream().map(BizFile::getGameId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(ids)) {
            List<BizGame> bizGames = bizGameService.listByIds(ids);
            Map<Long, String> map = bizGames.stream().collect(Collectors.toMap(BizGame::getId, BizGame::getName));

            vos.forEach(v -> {
                if (map.containsKey(v.getGameId())) {
                    v.setGameName(map.get(v.getGameId()));
                }
            });

        }

        return getDataTable(vos);
    }

    /**
     * 导出游戏附件列表
     */
    @RequiresPermissions("biz:file:export")
    @Log(title = "游戏附件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BizFile bizFile) {
        List<BizFile> list = bizFileService.selectBizFileList(bizFile);
        ExcelUtil<BizFile> util = new ExcelUtil<BizFile>(BizFile.class);
        return util.exportExcel(list, "游戏附件数据");
    }

    /**
     * 新增游戏附件
     */
    @RequiresPermissions("biz:file:add")
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        List<BizGame> games = bizGameService.selectBizGameList(new BizGame());
        mmap.put("games", games);

        return prefix + "/add";
    }

    /**
     * 新增保存游戏附件
     */
    @RequiresPermissions("biz:file:add")
    @Log(title = "游戏附件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam(value = "file", required = false) MultipartFile file, BizFile bizFile) throws IOException {
        if (file != null) {
            // 文件上传了, 需要重新处理一下
            bizFile.setName(StringUtils.isBlank(file.getOriginalFilename()) ? file.getName() : file.getOriginalFilename());
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            bizFile.setLink(fileName);
        }
        String link = bizFile.getLink();
        if (StringUtils.isNotEmpty(link)) {
            bizFile.setFileType(link.substring(link.lastIndexOf(".") + 1));
        }

        return toAjax(bizFileService.insertBizFile(bizFile));
    }

    /**
     * 修改游戏附件
     */
    @RequiresPermissions("biz:file:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        BizFile bizFile = bizFileService.selectBizFileById(id);
        mmap.put("bizFile", bizFile);

        // 获取游戏下拉
        List<BizGame> games = bizGameService.selectBizGameList(new BizGame());
        mmap.put("games", games);
        return prefix + "/edit";
    }

    /**
     * 修改保存游戏附件
     */
    @RequiresPermissions("biz:file:edit")
    @Log(title = "游戏附件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(value = "file", required = false) MultipartFile file, BizFile bizFile) throws IOException {
        if (file != null) {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 文件上传了, 需要重新处理一下
            String upName = StringUtils.isBlank(file.getOriginalFilename()) ? file.getName() : file.getOriginalFilename();

            // 判断一下有没有重复, 有重复直接拿过来用
            BizFile dbFile = bizFileService.selectBizFileById(bizFile.getId());
            if (!Objects.equals(upName, dbFile.getName())) {
                // 把旧的删除, 提升利用率
                String nLink = dbFile.getLink().substring(dbFile.getLink().lastIndexOf("upload") + 7);
                File absoluteFile = new File(filePath, nLink);
                if (absoluteFile.exists()) {
                    absoluteFile.delete();
                    LogUtils.getAccessLog().info("【文件变更】旧文件:{} 删除", absoluteFile.getAbsolutePath());
                }
            }
            bizFile.setName(upName);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            bizFile.setLink(fileName);

            if (Objects.equals(bizFile.getType(), "undefined")) {
                bizFile.setType(dbFile.getType());
            }
        }
        String link = bizFile.getLink();
        if (StringUtils.isNotEmpty(link)) {
            bizFile.setFileType(link.substring(link.lastIndexOf(".") + 1));
        }

        if (Objects.equals(bizFile.getFace(), "1")) {
            BizFile query = new BizFile();
            query.setFace("1");
            query.setGameId(bizFile.getGameId());
            List<BizFile> bizFiles = bizFileService.selectBizFileList(query);
            // 排除自己
            bizFiles.removeIf(f -> Objects.equals(f.getId(), bizFile.getId()));
            // 把其他首图改为非首图
            if (CollUtil.isNotEmpty(bizFiles)) {
                bizFiles.forEach(f -> {
                    f.setFace("0");
                    bizFileService.updateBizFile(f);
                });
            }
        }
        
        return toAjax(bizFileService.updateBizFile(bizFile));
    }

    /**
     * 删除游戏附件
     */
    @RequiresPermissions("biz:file:remove")
    @Log(title = "游戏附件", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(bizFileService.deleteBizFileByIds(ids));
    }
}
